package com.sonix.oidbluetooth;

import android.app.Dialog;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.sonix.app.App;
import com.sonix.base.BaseActivity;
import com.sonix.base.BindEventBus;
import com.sonix.oidbluetooth.view.SelectorView;
import com.sonix.util.Events;
import com.tqltech.tqlpencomm.PenCommAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 笔参数
 */
@BindEventBus
public class ParameterActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private static final int MSG_ONE = 1;  //更新时间
    private RelativeLayout rl_left;
    private TextView tv_title;

    private LinearLayout ll_name;
    private LinearLayout ll_rtc_time;
    private LinearLayout ll_auto_close_time;
    private LinearLayout ll_sensitivity;

    private TextView tv_name;
    private TextView tv_address;
    private TextView tv_bt_version;
    private TextView tv_mcu_version;

    private TextView tv_custom_id;
    private TextView tv_battery;
    private TextView tv_used_memory;
    private TextView tv_rtc_time;

    private TextView tv_auto_close_time;

    private TextView tv_sensitivity;
    private TextView tv_force_range;
    private TextView tv_element_code;

    private Switch sw_beep;
    private Switch sw_pressure_switch_on;
    private Switch sw_led;
    private Switch sw_save_log;
    private Switch sw_draw_stroke;
    private Switch sw_filter_algorithm;

    private PenCommAgent penCommAgent;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private long tmpTimer;
    private String mName;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_parameter;
    }

    @Override
    protected void initView() {
        rl_left = findViewById(R.id.rl_left);
        tv_title = findViewById(R.id.tv_title);
        rl_left.setOnClickListener(this);

        ll_name = findViewById(R.id.ll_name);
        ll_rtc_time = findViewById(R.id.ll_rtc_time);
        ll_auto_close_time = findViewById(R.id.ll_auto_close_time);
        ll_sensitivity = findViewById(R.id.ll_sensitivity);
        ll_name.setOnClickListener(this);
        ll_rtc_time.setOnClickListener(this);
        ll_auto_close_time.setOnClickListener(this);
        ll_sensitivity.setOnClickListener(this);

        tv_name = findViewById(R.id.tv_name);
        tv_address = findViewById(R.id.tv_address);
        tv_bt_version = findViewById(R.id.tv_bt_version);
        tv_mcu_version = findViewById(R.id.tv_mcu_version);

        tv_custom_id = findViewById(R.id.tv_custom_id);
        tv_battery = findViewById(R.id.tv_battery);
        tv_used_memory = findViewById(R.id.tv_used_memory);
        tv_rtc_time = findViewById(R.id.tv_rtc_time);

        tv_auto_close_time = findViewById(R.id.tv_auto_close_time);

        tv_sensitivity = findViewById(R.id.tv_sensitivity);
        tv_force_range = findViewById(R.id.tv_force_range);
        tv_element_code = findViewById(R.id.tv_element_code);

        sw_beep = findViewById(R.id.sw_beep);
        sw_pressure_switch_on = findViewById(R.id.sw_pressure_switch_on);
        sw_led = findViewById(R.id.sw_led);
        sw_save_log = findViewById(R.id.sw_save_log);
        sw_draw_stroke = findViewById(R.id.sw_draw_stroke);
        sw_filter_algorithm = findViewById(R.id.sw_filter_algorithm);
        sw_beep.setOnCheckedChangeListener(this);
        sw_pressure_switch_on.setOnCheckedChangeListener(this);
        sw_led.setOnCheckedChangeListener(this);
        sw_save_log.setOnCheckedChangeListener(this);
        sw_draw_stroke.setOnCheckedChangeListener(this);
        sw_filter_algorithm.setOnCheckedChangeListener(this);

    }

    @Override
    protected void initData() {
        tv_title.setText(getString(R.string.bcs));

        penCommAgent = PenCommAgent.GetInstance(getApplication());
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateStatus();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//               penCommAgent.getPenAllStatus();
//            }
//        }).start();
        penCommAgent.getPenAllStatus();
        handler.sendEmptyMessage(MSG_ONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(MSG_ONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveStatus(Events.ReceiveStatus receiveStatus) {
        Log.i(TAG, "receiveStatus: " + receiveStatus.penStatus);
        if (receiveStatus.penStatus != null) {

        } else {
            updateStatus();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveElementCode(Events.ReceiveElementCode elementCode) {
        String info = "SA:" + elementCode.code.SA + "/SB:" + elementCode.code.SB + "/SC:" + elementCode.code.SC + "/SD:" + elementCode.code.SD + "/index:" + elementCode.code.index;
        tv_element_code.setText(info);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveSetNameResponse(Events.ReceiveSetNameResponse status) {
        if (status.isSuccess) {
            App.mPenName = mName;
            App.mDeviceName = mName;
        }
        updateStatus();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.ll_name:
                showSetPenNameDialog();
                break;
            case R.id.ll_rtc_time:
                showSetPenRtcDialog();
                break;
            case R.id.ll_auto_close_time:
                showSetPenAutoCloseTimeDialog();
                break;
            case R.id.ll_sensitivity:
                showSetPenSensitivityDialog();
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        switch (compoundButton.getId()) {
            case R.id.sw_beep:
                Log.e(TAG, "蜂鸣器-------" + isChecked);
                App.tmp_mBeep = isChecked;
                penCommAgent.setPenBeepMode(isChecked);
                break;
            case R.id.sw_pressure_switch_on:
                Log.e(TAG, "压感开机-------" + isChecked);
                App.tmp_mPowerOnMode = isChecked;
                penCommAgent.setPenAutoPowerOnMode(isChecked);
                break;
            case R.id.sw_led:
                Log.e(TAG, "按键改变LED颜色-------" + isChecked);
                App.tmp_mEnableLED = isChecked;
                penCommAgent.setPenEnableLED(isChecked);
                break;
            case R.id.sw_save_log:
                Log.e(TAG, "保存日志功能-------" + isChecked);
                penCommAgent.setLogStatus(isChecked);
                break;
            case R.id.sw_draw_stroke:
                Log.e(TAG, "笔锋绘制功能-------" + isChecked);
                App.isDrawStoke = isChecked;
                break;
            case R.id.sw_filter_algorithm:
                Log.e(TAG, "过滤算法-------" + isChecked);
                penCommAgent.setIsSplitFiltration(isChecked);
                break;
        }
    }

    /**
     * 状态显示
     */
    private void updateStatus() {
        tv_name.setText(App.mPenName);
        tv_address.setText(App.mBTMac);
        tv_bt_version.setText(App.mFirmWare);
        tv_mcu_version.setText(App.mMCUFirmWare);

        tv_custom_id.setText(App.mCustomerID);
        tv_battery.setText(App.mBattery + "%");
        tv_used_memory.setText(App.mUsedMem + "%");
        if (tmpTimer != App.mTimer) {
            tv_rtc_time.setText(rtcTimeToDate(App.mTimer));
            tmpTimer = App.mTimer;
        }

        tv_auto_close_time.setText(Integer.toString(App.mPowerOffTime));
        tv_sensitivity.setText(Integer.toString(App.mPenSens));
        tv_force_range.setText(App.mTwentyPressure + "-" + App.mThreeHundredPressure);


        sw_beep.setChecked(App.mBeep);
        sw_pressure_switch_on.setChecked(App.mPowerOnMode);
        sw_led.setChecked(App.tmp_mEnableLED);

        sw_draw_stroke.setChecked(App.isDrawStoke);
        sw_save_log.setChecked(penCommAgent.getLogStatus());
        sw_filter_algorithm.setChecked(penCommAgent.getIsSplitFiltration());
    }

    /**
     * RTC时间转换为日期
     *
     * @param rtcTime rtc时间，起始时间2010年，单位秒
     * @return
     */
    private String rtcTimeToDate(long rtcTime) {
        long time = (1262275200L + rtcTime) * 1000; //毫秒
        Date date = new Date(time);
        String value = format.format(date);
        return value;
    }

    /**
     * 设置笔名dialog
     */
    private void showSetPenNameDialog() {
        Dialog dialog = new Dialog(this, R.style.customDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_name, null);
        EditText et_pen_name = view.findViewById(R.id.et_pen_name);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        TextView tv_ok = view.findViewById(R.id.tv_ok);

        et_pen_name.setText(tv_name.getText().toString());
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mName = et_pen_name.getText().toString();
                App.mPenName = mName;
                tv_name.setText(mName);
                penCommAgent.setPenName(mName);
                dialog.dismiss();
            }
        });

        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(layoutParams);

        dialog.show();
    }

    /**
     * 设置笔RTC时间dialog
     */
    private void showSetPenRtcDialog() {
        Dialog dialog = new Dialog(this, R.style.customDialog);
//        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_rtc, null);
//        LinearLayout ll_rtc_date = view.findViewById(R.id.ll_rtc_date);
//        LinearLayout ll_rtc_time = view.findViewById(R.id.ll_rtc_time);
//        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
//        TextView tv_ok = view.findViewById(R.id.tv_ok);
//
//        ll_rtc_date.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                showSetPenRtcDateDialog();
//            }
//        });
//        ll_rtc_time.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                showSetPenRtcTimeDialog();
//            }
//        });
//        tv_cancel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dialog.dismiss();
//            }
//        });
//        tv_ok.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dialog.dismiss();
//            }
//        });

        View view = LayoutInflater.from(this).inflate(R.layout.dialog_adjust_rtc, null);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        TextView tv_ok = view.findViewById(R.id.tv_ok);

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                penCommAgent.ReqAdjustRTC();
                penCommAgent.getPenRtc();
            }
        });

        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(layoutParams);

        dialog.show();
    }

    /**
     * 设置日期dialog
     */
    private void showSetPenRtcDateDialog() {
        Dialog dialog = new Dialog(this, R.style.customDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_rtc_date, null);

        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        TextView tv_ok = view.findViewById(R.id.tv_ok);

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(layoutParams);

        dialog.show();
    }


    /**
     * 设置时间dialog
     */
    private void showSetPenRtcTimeDialog() {
        Dialog dialog = new Dialog(this, R.style.customDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_rtc_time, null);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        TextView tv_ok = view.findViewById(R.id.tv_ok);

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });


        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(layoutParams);

        dialog.show();
    }

    /**
     * 设置笔自动关机时间dialog
     */
    private void showSetPenAutoCloseTimeDialog() {
        Dialog dialog = new Dialog(this, R.style.customDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_close_time, null);

        EditText et_pen_close_time = view.findViewById(R.id.et_pen_close_time);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        TextView tv_ok = view.findViewById(R.id.tv_ok);

        et_pen_close_time.setText(tv_auto_close_time.getText().toString());
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String time = et_pen_close_time.getText().toString();
                tv_auto_close_time.setText(time);
                penCommAgent.setPenAutoShutDownTime((short) Integer.parseInt(time));
                dialog.dismiss();
            }
        });

        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(layoutParams);

        dialog.show();
    }

    /**
     * 设置笔灵敏度dialog
     */
    private void showSetPenSensitivityDialog() {
        Dialog dialog = new Dialog(this, R.style.customDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_sensitivity, null);

        SelectorView iv_sensitivity_0 = view.findViewById(R.id.iv_sensitivity_0);
        SelectorView iv_sensitivity_1 = view.findViewById(R.id.iv_sensitivity_1);
        SelectorView iv_sensitivity_2 = view.findViewById(R.id.iv_sensitivity_2);
        SelectorView iv_sensitivity_3 = view.findViewById(R.id.iv_sensitivity_3);
        SelectorView iv_sensitivity_4 = view.findViewById(R.id.iv_sensitivity_4);
        iv_sensitivity_0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iv_sensitivity_0.toggle(true);
                iv_sensitivity_1.toggle(false);
                iv_sensitivity_2.toggle(false);
                iv_sensitivity_3.toggle(false);
                iv_sensitivity_4.toggle(false);
            }
        });

        iv_sensitivity_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iv_sensitivity_0.toggle(false);
                iv_sensitivity_1.toggle(true);
                iv_sensitivity_2.toggle(false);
                iv_sensitivity_3.toggle(false);
                iv_sensitivity_4.toggle(false);
            }
        });

        iv_sensitivity_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iv_sensitivity_0.toggle(false);
                iv_sensitivity_1.toggle(false);
                iv_sensitivity_2.toggle(true);
                iv_sensitivity_3.toggle(false);
                iv_sensitivity_4.toggle(false);
            }
        });

        iv_sensitivity_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iv_sensitivity_0.toggle(false);
                iv_sensitivity_1.toggle(false);
                iv_sensitivity_2.toggle(false);
                iv_sensitivity_3.toggle(true);
                iv_sensitivity_4.toggle(false);
            }
        });

        iv_sensitivity_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iv_sensitivity_0.toggle(false);
                iv_sensitivity_1.toggle(false);
                iv_sensitivity_2.toggle(false);
                iv_sensitivity_3.toggle(false);
                iv_sensitivity_4.toggle(true);
            }
        });

        if (App.mPenSens == 0) {
            iv_sensitivity_0.toggle(true);
            iv_sensitivity_1.toggle(false);
            iv_sensitivity_2.toggle(false);
            iv_sensitivity_3.toggle(false);
            iv_sensitivity_4.toggle(false);
        } else if (App.mPenSens == 1) {
            iv_sensitivity_0.toggle(false);
            iv_sensitivity_1.toggle(true);
            iv_sensitivity_2.toggle(false);
            iv_sensitivity_3.toggle(false);
            iv_sensitivity_4.toggle(false);
        } else if (App.mPenSens == 2) {
            iv_sensitivity_0.toggle(false);
            iv_sensitivity_1.toggle(false);
            iv_sensitivity_2.toggle(true);
            iv_sensitivity_3.toggle(false);
            iv_sensitivity_4.toggle(false);
        } else if (App.mPenSens == 3) {
            iv_sensitivity_0.toggle(false);
            iv_sensitivity_1.toggle(false);
            iv_sensitivity_2.toggle(false);
            iv_sensitivity_3.toggle(true);
            iv_sensitivity_4.toggle(false);
        } else if (App.mPenSens == 4) {
            iv_sensitivity_0.toggle(false);
            iv_sensitivity_1.toggle(false);
            iv_sensitivity_2.toggle(false);
            iv_sensitivity_3.toggle(false);
            iv_sensitivity_4.toggle(true);
        }

        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        TextView tv_ok = view.findViewById(R.id.tv_ok);

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (iv_sensitivity_0.isChecked()) {
                    tv_sensitivity.setText("0");
                    penCommAgent.setPenSensitivity((short) 0);
                    App.mPenSens = 0;
                } else if (iv_sensitivity_1.isChecked()) {
                    tv_sensitivity.setText("1");
                    penCommAgent.setPenSensitivity((short) 1);
                    App.mPenSens = 1;
                } else if (iv_sensitivity_2.isChecked()) {
                    tv_sensitivity.setText("2");
                    penCommAgent.setPenSensitivity((short) 2);
                    App.mPenSens = 2;
                } else if (iv_sensitivity_3.isChecked()) {
                    tv_sensitivity.setText("3");
                    penCommAgent.setPenSensitivity((short) 3);
                    App.mPenSens = 3;
                } else if (iv_sensitivity_4.isChecked()) {
                    tv_sensitivity.setText("4");
                    penCommAgent.setPenSensitivity((short) 4);
                    App.mPenSens = 4;
                }
                dialog.dismiss();
            }
        });

        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(layoutParams);

        dialog.show();
    }

    Date date;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_ONE:
                    String time = tv_rtc_time.getText().toString();
                    if (!TextUtils.isEmpty(time) && !time.equals("0")) {
                        try {
                            date = format.parse(time);
                            tv_rtc_time.setText(format.format(new Date(date.getTime() + 1000)));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                    handler.sendEmptyMessageDelayed(MSG_ONE, 1000);
                    break;
                default:
                    break;
            }

        }
    };
}
